<template>
  <div class="contract-tracking">
    <div class="page-header">
      <h1>合同追踪管理</h1>
      <button class="btn btn-success" @click="generateMockData">
        <i class="icon-test"></i>
        生成测试数据
      </button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-group">
          <label>合同编号</label>
          <input 
            v-model="searchParams.ContractNumber" 
            type="text" 
            placeholder="请输入合同编号" 
            class="form-control" 
          />
        </div>
        <div class="form-group">
          <label>合同类型</label>
          <select v-model="searchParams.ContractType" class="form-control">
            <option value="">全部</option>
            <option value="货主合同">货主合同</option>
            <option value="承运合同">承运合同</option>
            <option value="通用合同">通用合同</option>
          </select>
        </div>
        <div class="form-group">
          <label>合同方名称</label>
          <input 
            v-model="searchParams.OwnerName" 
            type="text" 
            placeholder="请输入合同方名称" 
            class="form-control" 
          />
        </div>
        <div class="form-group">
          <label>车牌号</label>
          <input 
            v-model="searchParams.LicensePlateNumber" 
            type="text" 
            placeholder="请输入车牌号" 
            class="form-control" 
          />
        </div>
        <div class="form-group">
          <label>异常状态</label>
          <select v-model="searchParams.HasAbnormal" class="form-control">
            <option :value="undefined">全部</option>
            <option :value="true">有异常</option>
            <option :value="false">无异常</option>
          </select>
        </div>
        <div class="form-actions">
          <button class="btn btn-primary" @click="searchContracts">搜索</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 合同追踪列表 -->
    <div class="table-section">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      <div v-else-if="contracts.length === 0" class="empty-container">
        <p>暂无数据</p>
      </div>
      <div v-else class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>合同编号</th>
              <th>合同标题</th>
              <th>合同类型</th>
              <th>合同方</th>
              <th>签订日期</th>
              <th>合同金额(元)</th>
              <th>订单信息</th>
              <th>车辆状态</th>
              <th>当前状态</th>
              <th>异常标记</th>
              <th>最后更新</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="contract in contracts" :key="contract.contractId">
              <td>{{ contract.contractNumber }}</td>
              <td>{{ contract.contractTitle }}</td>
              <td>
                <span class="badge badge-type">{{ contract.contractType }}</span>
              </td>
              <td>{{ contract.ownerName }}</td>
              <td>{{ formatDate(contract.signingDate) }}</td>
              <td class="text-right">{{ formatAmount(contract.contractAmount) }}</td>
              <td>
                <div class="order-info">
                  <div>订单号: {{ contract.orderInfo?.orderNumber || '-' }}</div>
                  <div>货物: {{ contract.orderInfo?.itemName || '-' }}</div>
                  <div>数量: {{ contract.orderInfo?.quantity || 0 }}</div>
                </div>
              </td>
              <td>
                <div v-if="contract.vehicles && contract.vehicles.length > 0">
                  <div v-for="vehicle in contract.vehicles" :key="vehicle.vehicleId" class="vehicle-info">
                    <div>{{ vehicle.licensePlateNumber }}</div>
                    <span 
                      :class="['badge', 'badge-' + getLocationStatusClass(vehicle.locationStatus)]"
                    >
                      {{ vehicle.locationStatus }}
                    </span>
                    <span 
                      :class="['badge', 'badge-' + getTransportStatusClass(vehicle.transportStatus)]"
                    >
                      {{ vehicle.transportStatus }}
                    </span>
                  </div>
                </div>
                <div v-else>-</div>
              </td>
              <td>
                <div class="status-text">{{ contract.currentStatus }}</div>
              </td>
              <td class="text-center">
                <span 
                  v-if="contract.hasAbnormal" 
                  class="badge badge-danger"
                >
                  异常
                </span>
                <span v-else class="badge badge-success">正常</span>
              </td>
              <td>{{ formatDateTime(contract.lastUpdateTime) }}</td>
              <td>
                <div class="action-buttons">
                  <button 
                    class="btn btn-sm btn-info" 
                    @click="viewDetail(contract.contractId, contract.contractType)"
                  >
                    查看详情
                  </button>
                  <button 
                    class="btn btn-sm btn-primary" 
                    @click="viewOnMap(contract)"
                  >
                    地图追踪
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div v-if="!loading && contracts.length > 0" class="pagination">
        <button 
          class="btn btn-secondary" 
          :disabled="!pagination.hasPreviousPage"
          @click="goToPage(pagination.pageIndex - 1)"
        >
          上一页
        </button>
        <span class="pagination-info">
          第 {{ pagination.pageIndex }} / {{ pagination.totalPages }} 页，
          共 {{ pagination.totalCount }} 条记录
        </span>
        <button 
          class="btn btn-secondary" 
          :disabled="!pagination.hasNextPage"
          @click="goToPage(pagination.pageIndex + 1)"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { contractTrackingApi } from '@/api'
import type { 
  ContractTrackingListParams, 
  ContractTrackingItem 
} from '@/types/api'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 搜索参数
const searchParams = reactive<ContractTrackingListParams>({
  PageIndex: 1,
  PageSize: 10,
  ContractNumber: '',
  ContractType: '',
  OwnerName: '',
  LicensePlateNumber: '',
  HasAbnormal: undefined
})

// 合同列表数据
const contracts = ref<ContractTrackingItem[]>([])
const loading = ref(false)

// 分页信息
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  totalPages: 0,
  hasPreviousPage: false,
  hasNextPage: false
})

// 加载合同追踪列表
const loadContracts = async () => {
  loading.value = true
  try {
    const response = await contractTrackingApi.getContractTrackingList(searchParams)
    
    if (response.code === 200 && response.data) {
      contracts.value = response.data.items || []
      
      // 更新分页信息
      pagination.pageIndex = response.data.pageIndex
      pagination.pageSize = response.data.pageSize
      pagination.totalCount = response.data.totalCount
      pagination.totalPages = response.data.totalPages
      pagination.hasPreviousPage = response.data.hasPreviousPage
      pagination.hasNextPage = response.data.hasNextPage
    } else {
      ElMessage.error(response.message || '查询失败')
    }
  } catch (error: any) {
    console.error('加载合同追踪列表失败:', error)
    ElMessage.error(error.message || '加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const searchContracts = () => {
  searchParams.PageIndex = 1
  loadContracts()
}

// 重置搜索
const resetSearch = () => {
  searchParams.ContractNumber = ''
  searchParams.ContractType = ''
  searchParams.OwnerName = ''
  searchParams.LicensePlateNumber = ''
  searchParams.HasAbnormal = undefined
  searchParams.PageIndex = 1
  loadContracts()
}

// 翻页
const goToPage = (page: number) => {
  searchParams.PageIndex = page
  loadContracts()
}

// 查看详情
const viewDetail = (contractId: number, contractType: string) => {
  router.push({
    name: 'ContractTrackingDetail',
    params: { id: contractId },
    query: { contractType }
  })
}

// 在地图上查看
const viewOnMap = (contract: ContractTrackingItem) => {
  router.push({
    name: 'ContractTrackingDetail',
    params: { id: contract.contractId },
    query: { 
      contractType: contract.contractType,
      tab: 'map' 
    }
  })
}

// 生成测试数据
const generateMockData = async () => {
  try {
    const result = await ElMessageBox.prompt('请输入合同ID和车牌号', '生成测试数据', {
      confirmButtonText: '生成',
      cancelButtonText: '取消',
      inputPattern: /^\d+$/,
      inputErrorMessage: '请输入有效的合同ID',
      inputPlaceholder: '请输入合同ID（如：1）'
    })

    if (result.value) {
      const contractId = parseInt(result.value)
      loading.value = true
      
      const response = await contractTrackingApi.generateMockData(contractId, '京A12345')
      
      if (response.code === 200) {
        ElMessage.success(`成功生成 ${response.data} 条追踪记录`)
        loadContracts()
      } else {
        ElMessage.error(response.message || '生成失败')
      }
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('生成测试数据失败:', error)
      ElMessage.error(error.message || '生成失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化金额
const formatAmount = (amount: number) => {
  if (!amount) return '0.00'
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 获取定位状态样式类
const getLocationStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    '有定位': 'success',
    '无定位': 'danger',
    '定位中': 'warning'
  }
  return statusMap[status] || 'secondary'
}

// 获取运输状态样式类
const getTransportStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    '未出发': 'secondary',
    '运输中': 'primary',
    '已到达': 'success',
    '异常': 'danger'
  }
  return statusMap[status] || 'secondary'
}

// 组件挂载时加载数据
onMounted(() => {
  loadContracts()
})
</script>

<style scoped>
.contract-tracking {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 5px;
  font-weight: 500;
  color: #666;
  font-size: 14px;
}

.form-control {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-control:focus {
  outline: none;
  border-color: #409eff;
}

.form-actions {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.btn-secondary {
  background-color: #909399;
  color: white;
}

.btn-secondary:hover {
  background-color: #a6a9ad;
}

.btn-secondary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-success {
  background-color: #67c23a;
  color: white;
}

.btn-success:hover {
  background-color: #85ce61;
}

.btn-info {
  background-color: #909399;
  color: white;
}

.btn-info:hover {
  background-color: #a6a9ad;
}

.btn-sm {
  padding: 5px 10px;
  font-size: 12px;
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.loading-container,
.empty-container {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1200px;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

.data-table th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.data-table td {
  font-size: 13px;
  color: #606266;
}

.data-table tbody tr:hover {
  background-color: #f5f7fa;
}

.text-right {
  text-align: right;
}

.text-center {
  text-align: center;
}

.badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 3px;
  font-size: 12px;
  font-weight: 500;
}

.badge-type {
  background-color: #e8f4ff;
  color: #409eff;
}

.badge-success {
  background-color: #f0f9ff;
  color: #67c23a;
}

.badge-primary {
  background-color: #ecf5ff;
  color: #409eff;
}

.badge-warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.badge-danger {
  background-color: #fef0f0;
  color: #f56c6c;
}

.badge-secondary {
  background-color: #f4f4f5;
  color: #909399;
}

.order-info {
  font-size: 12px;
  line-height: 1.6;
}

.vehicle-info {
  margin-bottom: 8px;
  line-height: 1.8;
}

.vehicle-info:last-child {
  margin-bottom: 0;
}

.status-text {
  max-width: 200px;
  white-space: normal;
  word-break: break-word;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}
</style>

